package com.egd.imapp.contoller.fragment;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;


import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.egd.imapp.R;
import com.egd.imapp.contoller.activity.contact.AddFriendActivity;
import com.egd.imapp.contoller.activity.contact.ContactDetailActivity;
import com.egd.imapp.contoller.activity.contact.GroupListActivity;
import com.egd.imapp.contoller.activity.contact.InviteActivity;
import com.egd.imapp.model.Model;
import com.egd.imapp.model.bean.UserInfo;
import com.egd.imapp.model.dao.ContactTableDao;
import com.egd.imapp.model.db.DBManager;
import com.egd.imapp.utils.Constant;
import com.egd.imapp.utils.CustomDialog;
import com.egd.imapp.utils.DevicePopWindow;
import com.egd.imapp.utils.SpUtils;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.interfaces.OnItemClickListener;
import com.hyphenate.easeui.interfaces.OnItemLongClickListener;
import com.hyphenate.easeui.modules.contact.EaseContactListFragment;
import com.hyphenate.easeui.modules.contact.model.EaseContactCustomBean;
import com.hyphenate.easeui.modules.menu.EasePopupMenuHelper;
import com.hyphenate.easeui.modules.menu.EasePopupWindow;
import com.hyphenate.easeui.modules.menu.EasePopupWindowHelper;
import com.hyphenate.easeui.widget.EaseSearchTextView;
import com.hyphenate.exceptions.HyphenateException;

import java.util.ArrayList;
import java.util.List;

public class ContactListFragment extends EaseContactListFragment implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener, OnItemLongClickListener {
    private ImageView iv_contact_add;
    private EaseSearchTextView tvSearch;
    private DevicePopWindow devicePopWindow;
    private static String TAG = "TAG";
    private ImageView iv_contact_red;
    private LocalBroadcastManager mLBM;
    private LinearLayout ll_contact_invite;
    private LinearLayout ll_contact_group;



    private BroadcastReceiver ContactInviteChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 更新红点显示
            iv_contact_red.setVisibility(View.VISIBLE);
            SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE, true);

        }
    };
    private BroadcastReceiver ContactChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 刷新页面
            onRefresh();
        }
    };
    private BroadcastReceiver GroupInviteChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 更新红点显示
            iv_contact_red.setVisibility(View.VISIBLE);
            SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE, true);
        }
    };
    private EasePopupMenuHelper menuHelper;


    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);

        addCommonTitle();

        //设置无数据时空白页面
        contactLayout.getContactList().getListAdapter().setEmptyLayoutResource(R.layout.imapp_layout_contact_list_empty);
        
        addHeader();

        // 初始化邀请信息条目的红点显示
        initInviteRedShow();

        Log.e(TAG, "initView: 初始化contactListFragement");

        // 注册广播
        mLBM = LocalBroadcastManager.getInstance(mContext);

        // 接收有好友时邀请的广播
        mLBM.registerReceiver(ContactInviteChangeReceiver, new IntentFilter(Constant.CONTACT_INVITE_CHANGED));

        // 联系人发生变化时发出的广播
        mLBM.registerReceiver(ContactChangeReceiver, new IntentFilter(Constant.CONTACT_CHANGED));

        // 接收有群邀请时发出的广播
        mLBM.registerReceiver(GroupInviteChangeReceiver, new IntentFilter(Constant.GROUP_INVITE_CHANGED));
    }

    private void initInviteRedShow() {

        // 初始化红点显示情况
        boolean isNewInvite = SpUtils.getInstance().getBoolean(SpUtils.IS_NEW_INVITE, false);
        Log.e(TAG, "initInviteRedShow: 初始化红点显示 "+ isNewInvite);
        iv_contact_red.setVisibility(isNewInvite ? View.VISIBLE : View.GONE);

        ll_contact_invite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 红点处理
                iv_contact_red.setVisibility(View.GONE);
                SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE, false);
                // 跳转到邀请信息列表界面
                startActivity(new Intent(mContext, InviteActivity.class));
            }
        });

    }

    private void addCommonTitle() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.imapp_layout_common_tilte, null);
        llRoot.addView(view,0);
        iv_contact_add = view.findViewById(R.id.iv_contact_add);
        tvSearch = view.findViewById(R.id.tv_search);
//        tvSearch.setHint("搜索");

        // 点击加号，将会弹出PopuWindow 这里初始化PopuWindow
        addPopuWindow();
    }

    /**
     * 初始化PopuWindow，并对其中的子view 设置点击监听
     */
    private void addPopuWindow() {
        devicePopWindow = new DevicePopWindow(mContext, R.layout.pop_window_device);
        View view = devicePopWindow.getContentView();

        view.findViewById(R.id.tv_contact_add_friend).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) { // 添加好友
                Intent intent = new Intent(mContext, AddFriendActivity.class);
                startActivity(intent);
            }
        });
        view.findViewById(R.id.tv_contact_find_group).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {// 找群
                Toast.makeText(mContext, "服务完善中...", Toast.LENGTH_SHORT).show();

            }
        });
        view.findViewById(R.id.tv_contact_scan).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {// 扫一扫
                Toast.makeText(mContext, "服务完善中...", Toast.LENGTH_SHORT).show();

            }
        });

    }

    /**
     * 添加头布局
     */
    public void addHeader() {
        View headerView = LayoutInflater.from(mContext).inflate(R.layout.contact_header_fragment, null);
        contactLayout.getContactList().addHeaderView(headerView);
        // 获取红点对象
        iv_contact_red = headerView.findViewById(R.id.iv_contact_red);
        Log.e(TAG, "addHeader: 添加头布局 "+ iv_contact_red.getVisibility(), null);
        // 获取邀请信息条目的对象
        ll_contact_invite = headerView.findViewById(R.id.ll_contact_invite);
        ll_contact_group = headerView.findViewById(R.id.ll_contact_group);

//        View viewById = contactLayout.getContactList().findViewById(R.id.ll_contact_invite);
//        Log.e(TAG, "addHeader: viewById "+ viewById,null );
    }

    @Override
    public void initListener() {
        super.initListener();
        contactLayout.getSwipeRefreshLayout().setOnRefreshListener(this);
        tvSearch.setOnClickListener(this);
        iv_contact_add.setOnClickListener(this);

        contactLayout.getContactList().setOnCustomItemClickListener(this);

        ll_contact_group.setOnClickListener(this);

        contactLayout.getContactList().setOnItemLongClickListener(this);

    }

    @Override
    public void initData() {

        menuHelper = contactLayout.getContactList().getMenuHelper();

        menuHelper.setOnPopupMenuItemClickListener(this);

//        super.initData();
        // 从环信服务器中获取所有的联系人信息
        getContactsFromHxServer();
    }

    private void getContactsFromHxServer() {
        Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                List<String> hxids = null;
                try {
                    // 获取所有好友的环信 id
                    hxids = EMClient.getInstance().contactManager().getAllContactsFromServer();

                    if (hxids != null && hxids.size() >= 0){

                        String currentUser = EMClient.getInstance().getCurrentUser();
                        Log.e(TAG, "run: 当前登录用户 currentUser = " + currentUser );

                        List<UserInfo> contacts = new ArrayList<>();

                        for (String hxid : hxids){
                            UserInfo userInfo = new UserInfo(hxid);
                            contacts.add(userInfo);
                            Log.e(TAG, "run: 远程服务器中的好友列表：name = " + userInfo.getHxid());
                        }

                        // 保存好友信息到本地数据库
                        DBManager dbManager = getDbManager();
                        if (dbManager == null){
                            return;
                        }
                        Log.e(TAG, "run: 远程服务器中的好友人数： nums = " + contacts.size() );
                        ContactTableDao contactTableDao = dbManager.getContactTableDao();

                        contactTableDao.saveContacts(contacts, true);

                        if (mContext == null){
                            return;
                        }

                        // 刷新好友页面
                        mContext.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                refreshContacts();
//                                onRefresh();
                            }
                        });
                    }

                } catch (HyphenateException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private void refreshContacts() {

        // 获取数据
        DBManager dbManager = getDbManager();
        if (dbManager == null){
            return;
        }
        List<UserInfo> userInfos = dbManager.getContactTableDao().getContacts();
        Log.e(TAG, "run: 本地数据库中的好友人数： nums = " + userInfos.size() );


        List<EaseUser> contacts = new ArrayList<>();
        if (userInfos != null && userInfos.size() >= 0){
            for (UserInfo userInfo : userInfos){
                EaseUser easeUser = new EaseUser();
                easeUser.setSign(userInfo.getHxid());
                easeUser.setUsername(userInfo.getName());
                easeUser.setNickname(userInfo.getNick());
//                easeUser.setAvatar(userInfo.getPhoto());
                contacts.add(easeUser);
                Log.e(TAG, "refreshContacts: 本地数据库中的好友 contacts name = " + userInfo.getHxid() );
            }

            contactLayout.getContactList().setData(contacts);
        }
    }

    private DBManager getDbManager() {
        return Model.getInstance().getDbManager();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_search :
                Toast.makeText(mContext, "服务完善中tv_search...", Toast.LENGTH_SHORT).show();

//                SearchFriendsActivity.actionStart(mContext);
                break;
            case R.id.iv_contact_add:
                devicePopWindow.showAsDropDown(iv_contact_add);
//                Toast.makeText(mContext, "服务完善中iv_contact_add...", Toast.LENGTH_SHORT).show();
                break;
            case R.id.ll_contact_group: // 跳转到群组界
                jumpGroupListActivity();
                break;
            default:
                break;
        }
    }

    private void jumpGroupListActivity() {
        Intent intent = new Intent(mContext, GroupListActivity.class);

        startActivity(intent);

    }

    @Override
    public void onRefresh() {
        refreshContacts();
        initInviteRedShow();
//        initData();
    }

    @Override
    public void onItemClick(View view, int position) {
        int itemCount = contactLayout.getContactList().getListAdapter().getItemCount();
        Log.e(TAG, "onItemClick: "+ itemCount );

        position = position > 0 ? position - 1 : 0;
        super.onItemClick(view, position);
        EaseUser user = contactLayout.getContactList().getItem(position);
//        ContactDetailActivity.actionStart(mContext, item);
        Intent intent = new Intent(mContext, ContactDetailActivity.class);
        intent.putExtra("user", user);
        startActivity(intent);
//        Toast.makeText(mContext, "打开好友 user = " + user.getUsername(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onItemLongClick(View view, int position) {
//        Toast.makeText(mContext, " 条目长按监听 position = " + position, Toast.LENGTH_SHORT).show();

        menuHelper.addItemMenu(1, R.id.action_friend_block, 2, "移入到黑名单");
        menuHelper.addItemMenu(1, R.id.action_friend_delete, 1, "删除联系人");
        menuHelper.initMenu(view);
        menuHelper.show();
        return true;
    }

    @Override
    public boolean onMenuItemClick(MenuItem item, int position) {
        int itemCount = contactLayout.getContactList().getListAdapter().getItemCount();
        Log.e(TAG, "onItemClick: "+ itemCount );
        position = position >0 ? position - 1 : 0;

        EaseUser user = contactLayout.getContactList().getItem(position);
        switch (item.getItemId()) {
            case R.id.action_friend_block :
                Toast.makeText(mContext, "服务完善中" , Toast.LENGTH_SHORT).show();

//                mViewModel.addUserToBlackList(user.getUsername(), false);
                return true;
            case R.id.action_friend_delete:

                showDeleteDialog(user);
                return true;
        }
        return super.onMenuItemClick(item, position);
    }

    private void deleteContact(EaseUser user) {
        Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    EMClient.getInstance().contactManager().deleteContact(user.getUsername());

                    if (mContext == null){
                        return;
                    }
                    // 本地数据库的更新
                    Model.getInstance().getDbManager().getContactTableDao().deleteContactByHxId(user.getUsername());

                    mContext.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, " 删除"+ user.getUsername() +" 成功", Toast.LENGTH_SHORT).show();
                            contactLayout.getContactList().notifyDataSetChanged();

                            onRefresh();
                        }
                    });

                } catch (HyphenateException e) {
                    e.printStackTrace();

                    if (mContext == null){
                        return;
                    }

                    mContext.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, " 删除"+ user.getUsername() +" 失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });

    }

    private void showDeleteDialog(EaseUser user) {
        CustomDialog customDialog = new CustomDialog(mContext);
        customDialog.setMsg("您确定删除 " + user.getUsername() + " 好友吗？")
                .setNegative("取消")
                .setPositive("确定")
                .setOnClickButtonListener(new CustomDialog.OnClickButtonListener() {
                    @Override
                    public void OnClickNegative() {
                        customDialog.dismiss();
                    }

                    @Override
                    public void OnClickPositive() {
                        deleteContact(user);
                        customDialog.dismiss();
                    }
                }).show();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        // 关闭广播
        mLBM.unregisterReceiver(ContactInviteChangeReceiver);

        mLBM.unregisterReceiver(ContactChangeReceiver);

        mLBM.unregisterReceiver(GroupInviteChangeReceiver);
    }

}
